//
// Copyright (c) 2014, 保留所有权利。
//
// ContractSync.java
//
// 作    者：王红燕
// 当前版本：1.0
// 2014 下午1:16:13
//
// 
//
package com.vanke.agent.sync;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;


import org.apache.log4j.Logger;

import com.vanke.agent.ADataSource;
import com.vanke.agent.C;
import com.vanke.agent.common.CstUtil;

/**
 *
 */
public class EmpInfoSync extends AgentSync {
	Logger log = Logger.getLogger(EmpInfoSync.class);
	String table = "empinfo_my";
	String fields = C.FIELDS_EMPINFO;

	@Override
	public void sync() {
		log.info("=============sync new empinfo===========");
		Connection con = ADataSource.getConnection(ADataSource.SCHEMA_EM);
		Connection wcon = ADataSource.getConnection(ADataSource.SCHEMA_BIZ);

		try {

			String querySql = "SELECT " + fields + "  FROM " + table;

			String insertSql = CstUtil.formatInsertSql(table, fields);
			String updateSql = CstUtil.formatUpdateSql(table, fields);
			updateSql += " where pernr =?";
			//String sql = insertSql + " ON DUPLICATE KEY " + updateSql;
			//log.info("execute insert or update sql: " + sql);
			PreparedStatement wpstmt = wcon.prepareStatement(insertSql);
			PreparedStatement dataUpdatePs = wcon.prepareStatement(updateSql);

			int columns = fields.split(",").length;

			PreparedStatement pstmt = con.prepareStatement(querySql);

			ResultSet rs = pstmt.executeQuery();
			int count = 0;
			int updateFlag = 0;
			if (!rs.next()) {
				log.info("no empinfo is created");
				ADataSource.close(rs);
				ADataSource.close(pstmt);
				return;
			}

			PreparedStatement dataps = wcon
					.prepareStatement("select pernr from empinfo_my");
			ResultSet datars = dataps.executeQuery();
			Map<String, Boolean> dataGuidMap = new HashMap<String, Boolean>();
			while (datars.next()) {
				dataGuidMap.put(datars.getString("pernr").trim(), true);
			}

			ADataSource.close(datars);
			ADataSource.close(dataps);

			do {
				try {
					for (int i = 1; i <= columns; i++) {
						wpstmt.setString(i, rs.getString(i));
						dataUpdatePs.setString(i, rs.getString(i));
					}
					//wpstmt.setString(15, rs.getString("sname"));
					/** 存在该记录就更新否则插入 **/
					if (dataGuidMap.containsKey(rs.getString("pernr").trim())) {
						dataUpdatePs.setString(15, rs.getString("pernr"));
						dataUpdatePs.executeUpdate();
						updateFlag++;
					} else {
						wpstmt.executeUpdate();
						count++;
					}

				} catch (Exception e) {
					e.printStackTrace();
					log.error(e);
				}

			} while (rs.next());

			// 关闭
			ADataSource.close(rs);
			ADataSource.close(pstmt);
			ADataSource.close(wpstmt);
			ADataSource.close(dataUpdatePs);

			log.info(count + " empinfo save ");
			log.info(updateFlag + " empinfo update ");
			log.info("=============sync empinfo end===========");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ADataSource.close(con);
			ADataSource.close(wcon);
		}
	} // ~sync

}
